import http from 'wechat-http'

http.baseURL = 'https://live-api.itheima.net'
//挂载到全局

// 普通的模块导出
//请求拦截器
http.intercept.request = function (options) {
  //TODO

  const { token } = getApp()
  if (!options.header) {
    options.header = {
      Authorization: `Bearer ${token}`
    }
  }
  return options
}
//响应拦截器
http.intercept.response = async function ({ data, config }) {
  // const data = response.data
  if (data.code === 401) {
    if (config.url.includes('/refreshToken')) {
      const currentPage = getCurrentPages().pop()
      const route = currentPage.route
      return wx.redirectTo({
        url: '/pages/login/index?route=' + route
      })
    }
    const app = getApp()
    const res = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: 'Bearer ' + app.refreshToken
      }
    })
    if (res.code !== 10000) return wx.utils.toast('更新token失败!')
    // 重新存储新的 token
    app.setToken('token', res.data.token)
    app.setToken('refreshToken', res.data.refreshToken)
    config = Object.assign(config, { header: { Authorization: 'Bearer ' + res.data.token } })
    return http(config)
  }
  return data
}
wx.http = http
export default http
